#include "stdafx.h"
#include <Windows.h>
#include <dbghelp.h>
#include <shellapi.h>
#include <shlobj.h>
#include <stdio.h>
#include <time.h>
#include "MiniDump.h"

#pragma comment(lib, "dbghelp.lib")

LONG WINAPI GenerateDump(struct _EXCEPTION_POINTERS *pExceptionPointers)
{
	LONG ret = EXCEPTION_EXECUTE_HANDLER;
	BOOL bMiniDumpSuccessful;
	TCHAR szPath[MAX_PATH];
	DWORD dwBufferSize = MAX_PATH;
	HANDLE hDumpFile;
	SYSTEMTIME stLocalTime;
	MINIDUMP_EXCEPTION_INFORMATION ExpParam;

	GetLocalTime( &stLocalTime );
	GetTempPath( dwBufferSize, szPath );

	time_t curTime;
	tm timeinfo;
	time(&curTime);
	localtime_s(&timeinfo,&curTime);

	char dumpName[256] = {'\0'};
	sprintf_s(dumpName, 256, "%d-%d-%d-%d-%d-%d.dmp", 
		timeinfo.tm_year + 1900, 
		timeinfo.tm_mon + 1,
		timeinfo.tm_mday,
		timeinfo.tm_hour,
		timeinfo.tm_min,
		timeinfo.tm_sec);
	hDumpFile = CreateFileA(dumpName, GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, 0, NULL);

	ExpParam.ThreadId = GetCurrentThreadId();
	ExpParam.ExceptionPointers = pExceptionPointers;
	ExpParam.ClientPointers = TRUE;

	bMiniDumpSuccessful = MiniDumpWriteDump(GetCurrentProcess(), GetCurrentProcessId(),
		hDumpFile, MiniDumpWithDataSegs, &ExpParam, NULL, NULL);

	int i = GetLastError();
	HRESULT hr = HRESULT_FROM_WIN32(i);

	return ret;
}